package com.hkh.erp.system.api;

import com.hkh.erp.common.api.RespException;
import com.hkh.erp.common.api.RespResult;
import com.hkh.erp.common.api.RespStatus;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.List;

/**
 * 全局异常处理
 * @author huangkh
 */
@RestControllerAdvice
@Slf4j
public class GlobalExceptionHandler {

    private final String SYS_ERROR = "系统错误";

    @ResponseBody
    @ExceptionHandler(RespException.class)
    public Object handleRespException(RespException e) {
        e.printStackTrace();
        log.error(e.getMessage(),e);
        RespResult respResult = new RespResult(e.getCode(),e.getDescribe(),null);
        return respResult;
    }

    @ResponseBody
    @ExceptionHandler(Exception.class)
    public Object handleException(Exception e) {
        e.printStackTrace();
        log.error(e.getMessage(),e);
        RespResult respResult = new RespResult(RespStatus.ERROR.getCode(),SYS_ERROR,null);
        return respResult;
    }
    /**
     * 校验错误拦截处理
     * @param exception 错误信息集合
     * @return 错误信息
     */
    @ExceptionHandler(MethodArgumentNotValidException.class)
    public Object validationBodyException(MethodArgumentNotValidException exception) {
        BindingResult result = exception.getBindingResult();
        if (result.hasErrors()) {
            List<ObjectError> errors = result.getAllErrors();
            errors.forEach(p -> {
                FieldError fieldError = (FieldError)p;
            });
            log.error(exception.getMessage(),exception);
            RespResult respResult = new RespResult(RespStatus.ERROR.getCode(),result.getFieldError() == null ? "请求参数有误" : result.getFieldError().getDefaultMessage(),null);
            return respResult;
        }
        log.error(exception.getMessage(),exception);
        return new RespResult(RespStatus.ERROR.getCode(),SYS_ERROR,null);
    }



}

